import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Button, Typography, Tag, message, Spin } from 'antd';
import styled from 'styled-components';
import api from '../services/api';
import { InterestTag, User } from '../store/slices/userSlice';

const { Title, Text } = Typography;

const StyledCard = styled(Card)`
    margin: 0 auto;
    max-width: 600px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
`;

const TagContainer = styled.div`
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 16px 0;
`;

const StyledTag = styled(Tag)`
    margin: 4px;
    padding: 8px 16px;
    font-size: 16px;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
        transform: scale(1.05);
    }
`;

const ButtonContainer = styled.div`
    display: flex;
    justify-content: space-between;
    margin-top: 24px;
`;

const InterestTagsPage: React.FC = () => {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [selectedTags, setSelectedTags] = useState<InterestTag[]>([]);
    const [availableTags, setAvailableTags] = useState<InterestTag[]>([]);

    useEffect(() => {
        const fetchTags = async () => {
            try {
                setLoading(true);
                const token = localStorage.getItem('userToken');
                if (!token) {
                    message.error('未认证，请先登录。');
                    navigate('/login');
                    return;
                }

                // 获取所有可用标签
                const tagsResponse = await api.tags.getAllTags();
                if (tagsResponse.success && tagsResponse.tags) {
                    setAvailableTags(tagsResponse.tags);

                    // 获取用户已选标签
                    const userResponse = await api.auth.getUserProfile(token);
                    if (userResponse.success && userResponse.user?.interestTags) {
                        // 将用户已选标签转换成 InterestTag 对象
                        const selectedUserTags = userResponse.user.interestTags
                            .map(userTag => tagsResponse.tags?.find(availableTag => availableTag.id === userTag.id))
                            .filter((tag): tag is InterestTag => tag !== undefined);
                        setSelectedTags(selectedUserTags);
                    }
                }

            } catch (error) {
                console.error('Error fetching tags:', error);
                message.error('获取标签失败');
            } finally {
                setLoading(false);
            }
        };

        fetchTags();
    }, [navigate]);

    const handleTagClick = (tag: InterestTag) => {
        setSelectedTags(prev => {
            // 检查标签是否已经被选中
            const isSelected = prev.some(t => t.id === tag.id);

            if (isSelected) {
                // 如果已选中，则移除它
                return prev.filter(t => t.id !== tag.id);
            } else {
                // 如果未选中，则检查添加后是否会超出限制
                const maxTags = 9; // 定义允许的最大标签数量
                if (prev.length >= maxTags) {
                    message.warning(`最多只能选择 ${maxTags} 个兴趣标签。`);
                    return prev; // 不添加新标签
                } else {
                    // 添加新标签
                    return [...prev, tag];
                }
            }
        });
    };

    const handleSaveTags = async () => {
        try {
            setSaving(true);
            const token = localStorage.getItem('userToken');
            if (!token) {
                message.error('未认证，请先登录。');
                navigate('/login');
                return;
            }

            // 明确定义 payload 类型
            type UpdateTagsPayload = Partial<Omit<User, 'interestTags'>> & { interestTags?: number[] };

            const payload: UpdateTagsPayload = {
                interestTags: selectedTags.map(tag => tag.id)
            };

            const response = await api.auth.updateUserProfile(token, payload);

            if (response.success) {
                message.success('兴趣标签保存成功');
                navigate('/profile');
            } else {
                message.error(response.message || '保存失败');
            }
        } catch (error) {
            console.error('Error saving tags:', error);
            message.error('保存失败');
        } finally {
            setSaving(false);
        }
    };

    if (loading) {
        return (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
                <Spin size="large" />
            </div>
        );
    }

    return (
        <div>
            <StyledCard>
                <Title level={4}>选择你的兴趣标签</Title>
                <Text type="secondary">选择你感兴趣的标签，这将帮助我们为你推荐更相关的内容</Text>

                <TagContainer>
                    {availableTags.map(tag => (
                        <StyledTag
                            key={tag.id}
                            color={selectedTags.some(t => t.id === tag.id) ? 'blue' : 'default'}
                            onClick={() => handleTagClick(tag)}
                        >
                            {tag.name}
                        </StyledTag>
                    ))}
                </TagContainer>

                <ButtonContainer>
                    <Button onClick={() => navigate('/profile')}>返回</Button>
                    <Button
                        type="primary"
                        onClick={handleSaveTags}
                        loading={saving}
                    >
                        保存
                    </Button>
                </ButtonContainer>
            </StyledCard>
        </div>
    );
};

export default InterestTagsPage; 